// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
});

// 云函数入口函数
exports.main = async (event, context) => {
    const db = cloud.database();
    const _ = db.command;
    const {seasonId, activityId} = event;

    try {
        return await db.collection('activity').where({
            _id: activityId
        }).remove().then(async () => {
            // 删除赛季中的对应数据
            const season = await db.collection('season').doc(seasonId).get();
            const activityIds = season.data.activityIds.filter((id) => id !== activityId);
            return db.collection('season').doc(seasonId).update({
                data: {
                    activityIds
                }
            })
        }).then(async () => {
            // 删除个人信息中活动记录
            await db.collection('user').where({
                'activities.id': activityId
            }).update({
                data: {
                    activities: _.pull({
                        id: activityId
                    })
                }
            })
        })
    } catch (e) {
        console.log(e);
    }
}
